using System;
using System.IO;
using System.Web;
using System.Data;
using System.Threading;
using System.Collections;
using System.Configuration; 
using System.Xml;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Web.Security;
using System.Configuration.Provider;
using System.Collections.Specialized;


namespace ACM.cmsarea08
{
	/// <summary>
	/// Classe da inserire in Sessione, contiene i dati utente "loggato";
	/// </summary>
	public class UserLogged {
		private string _username;
		private string _cognome;
		private string _nome;
		private string _idutente;
		private string _emailutente;
		private string _pref_language;
		private string _tinymode;
		private bool _dummyadmin;
		private object _params ;
		private bool _editmode;
		//private string[] _ruoli;
		private bool _autorizzato;
		private Ruolo _ruolo;
		public UserLogged() { 
			_username =		string.Empty;
			_idutente = 	string.Empty;
			_emailutente=	string.Empty;
			_nome = 	string.Empty;
			_cognome=	string.Empty;			
			_pref_language = ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita;
			//_ruoli = 		new string[0];
			_autorizzato= 	false;
			_editmode = false;
			_dummyadmin=true;
			_ruolo = new Ruolo();
			_params=null;
		}
		public UserLogged(string username, string idutente, string nome, string cognome, string email, string language, string[] ruoli, bool autorizzato) {
			_username = username;
			_idutente = idutente;
			_nome = nome;
			_cognome = cognome;
			_emailutente = email;
			_pref_language = language;
			//_ruoli = ruoli;
			_autorizzato = autorizzato;
			_editmode = false;
			_ruolo = new Ruolo();
			this.PrefLanguage = language;
			//_ruolo.DependSon= ruoli;
			_dummyadmin=true;
			if(_ruolo.Name.ToLower()=="sysadm") _dummyadmin=false;
			_params=null;
			Users.CurrentUser = this;
			
		}
		public UserLogged(string username, string idutente, string email, string[] ruoli) {
			_username =		username;
			_idutente = 	idutente;
			_nome = 	string.Empty;
			_cognome=	string.Empty;			
			_emailutente=	email;
			_pref_language = ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita;
			//_ruoli = 		ruoli;
			_autorizzato= 	false;	
			_editmode = false;
			_ruolo = new Ruolo();
			//_ruolo.DependSon= ruoli;
			_dummyadmin=true;
			if(_ruolo.Name.ToLower()=="sysadm") _dummyadmin=false;	
			_params=null;
			Users.CurrentUser = this;
			
			
		}
		public UserLogged(string username, string idutente, string email, string lingua, string[] ruoli) {
			_username =		username;
			_idutente = 	idutente;
			_nome = 	string.Empty;
			_cognome=	string.Empty;			
			_emailutente=	email;
			_pref_language = lingua;
			//_ruoli = 		ruoli;
			_autorizzato= 	false;	
			_editmode = false;
			_ruolo = new Ruolo();
			//_ruolo.DependSon= ruoli;
			_dummyadmin=true;
			if(_ruolo.Name.ToLower()=="sysadm") _dummyadmin=false;
			_params=null;
			Users.CurrentUser = this;
		}
		public UserLogged(string username, string idutente, string email, string[] ruoli,bool authorized) {
			_username =		username;
			_idutente = 	idutente;
			_nome = 	string.Empty;
			_cognome=	string.Empty;			
			_emailutente=	email;
			_pref_language = ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita;
			//_ruoli = 		ruoli;
			_autorizzato= 	authorized;	
			_editmode = false;
			_ruolo = new Ruolo();
//			_ruolo.DependSon= ruoli;
			_dummyadmin=true;
			if(_ruolo.Name.ToLower()=="sysadm") _dummyadmin=false;
			_params=null;
			Users.CurrentUser = this;
		}		
		public override string ToString() {
			return UserName + ", " + NomeCognome;
		}
		public string UserName {
			get {
				return _username;
			}
		}
		public string Nome {
			get {
				return _nome;
			}
		}		
		public string Cognome {
			get {
				return _cognome;
			}
		}		
		public string NomeCognome{
			get {
				return _nome + " " + _cognome;
			}
		}
		public string CognomeNome{
			get {
				return _nome + " " + _cognome;
			}
		}		
		public string IdUtente {
			get {
				return _idutente;
			}
		}
		public string Email {
			get {
				return _emailutente;
			}
		}
		public object Parametri {
			get {
				return _params;
			}
			set {
				_params = value;
			}
		}		
		public string PrefLanguage {
			get {
				if(HttpContext.Current==null)
					return _pref_language;
				if(HttpContext.Current.Request.Cookies["UserLang_"+this.Guid]!=null) {
					return HttpContext.Current.Request.Cookies["UserLang_"+this.Guid].Value;
				} else
					return _pref_language;
			}
			set {
				if(HttpContext.Current==null) return;
				if(HttpContext.Current.Request.Cookies["UserLang_"+this.Guid]==null) {
					HttpCookie myCookie = new HttpCookie("UserLang_"+this.Guid);
					myCookie.Value = value;
					myCookie.Expires = DateTime.Now.AddDays(1);
					HttpContext.Current.Response.Cookies.Add(myCookie);
				} else {
					HttpContext.Current.Response.Cookies["UserLang_"+this.Guid].Value = value;
				}
			}
		}
		public bool Autorizzato {
			get {
				return _autorizzato;
			}
		}
		public bool EditMode {
			get {
				return this._editmode;
			}
			set {
				_editmode = value;
			}
		}
		public Ruolo Role{
			get {
				return _ruolo;
			}
			set {
				_ruolo=value;
			}
		}
		public string[] Ruoli {
			get {
				if(_ruolo!=null) 
					return _ruolo.DependSon;
				else
					return new string[0];
			}
		}
		public string Guid {
			get {
				return HttpContext.Current.Session.SessionID;
			}
		}
		public string SetEmail {
			set {
				_emailutente = value;
			}
		}
		public string SetPrefLanguage {
			set {
				_pref_language = value;
			}
		}
		public string EditorType {
			get {
				return _tinymode;
			}
			set {
				_tinymode = value;
			}
		}
		public bool isPublisher{
			get {
				if(this.Role.Score>200)
					return false;
				return true;
			}
		}
		public bool SimpleAdmin{
			get {
				return _dummyadmin;
			}
			set {
				_dummyadmin=value;
			}
		}
		public void SetUserName (string newUserName) {
			this._username = newUserName;
		}
		
		public bool isRuolo(string ruolo) {
			//verifica la presenta del ruolo 
			if(_ruolo==null)
				return false;
			else
				return System.Array.Exists<string>(_ruolo.DependSon,new Predicate<string>(ruolo.Trim().Equals));
		}
		public bool isRuolo(string[] ruoli) {
			bool reso = false;
			if(_ruolo==null)
				return false;
			
			for(int o=0;o<ruoli.Length;o++){
				if(System.Array.Exists<string>(_ruolo.DependSon,new Predicate<string>(ruoli[o].Trim().Equals)))
						   reso = true;
			}
			return reso;
		}
		private string getParamValue (string attrib,ref XmlDocument xdoc) {
			System.Xml.XmlNode xn = xdoc.SelectSingleNode("//attrib/param[pnome='"+attrib+"']/pvalore");			
			if(xn==null) { 
				xn = xdoc.SelectSingleNode("//impostazioni/set[nome='"+attrib+"']/valore");
				if(xn==null) return string.Empty;
				else return xn.InnerText;
			}
			return xn.InnerText;
		}
		
		public void setParametri(object newParam) {
			if(newParam==null) return;
			this._params = newParam;
			AnalizeParams(this._params);
		}
		public void AnalizeParams(object cparams) {
//			HttpContext.Current.Response.Write("LOAD ANALIZ");
			if(cparams==null) return;
//			HttpContext.Current.Response.Write("LOAD ANALIZ NO NULL");
			System.Xml.XmlDocument xpar = new XmlDocument();			
			string parametri = "";
			object d = ACM.cmsarea08.formdataadapter.Adapter.Decompress(cparams);
			if(d!=null) 
				d = ACM.cmsarea08.formdataadapter.Adapter.ObjectToItanData(d);
			if(d!=null) {
				if(d is byte[]) {
					parametri = System.Text.Encoding.UTF8.GetString((byte[])d);
				} else parametri= d.ToString();
			}
//			HttpContext.Current.Response.Write("LOAD ANALIZ:" +parametri);
			if(string.IsNullOrEmpty(parametri)) return;
			try {
				xpar.LoadXml(parametri);
			} catch (Exception e) {
				xpar = null;
				return;
			} 
//			HttpContext.Current.Response.Write("QUI CI ARRIVO: " + xpar.InnerXml);
			//ora che sono qui.. mi auto imposto i valori tipo nome cognome ed email..in base al mio profilo..
			//cerca name, surname, nome, cognome:
			string nm = getParamValue("name",ref xpar);
			if(nm!=string.Empty) this._nome = nm;
			nm = getParamValue("nome",ref xpar); 
			if(nm!=string.Empty) this._nome = nm;
			
			nm = getParamValue("surname",ref xpar);
			if(nm!=string.Empty) this._cognome = nm;
			nm = getParamValue("cognome",ref xpar); 
			if(nm!=string.Empty) this._cognome = nm;
			xpar=null;
			nm =string.Empty;
		}
	}
	public sealed class Users {
		static Users() { }
		
		public static UserLogged CurrentUser {
			get {
				if(HttpContext.Current==null) return null;
				
				if(HttpContext.Current.Session["utente_loggato"]!=null) 
					return (UserLogged)HttpContext.Current.Session["utente_loggato"];
				else
					return new UserLogged("Anonimo","-1","anonymous@fltlab.net",new string[1] {"guest"}); //valore 166 per prove lockid
			}
			set {
				if(HttpContext.Current==null) return ;
				HttpContext.Current.Session["utente_loggato"]=value;
			}
			
		}
		/* 
		
		public event EventHandler UserLogged;
		public event EventHandler UserLogout;
		public event EventHandler UserTimeout;
		protected void OnUserLogged(UserEventArgs e)
		{
			if(UserLogged != null) UserLogged(this, e);
		}
		protected void OnUserLogout(UserEventArgs  e)
		{
			if(UserLogout != null) UserLogout(this, e);
		}	
		protected void OnUserTimeout(UserEventArgs  e)
		{
			if(UserTimeout != null) UserTimeout(this, e);
		}			
		*/
		
	}
	public class UserEventArgs : System.EventArgs {
		private string _username;
		private string _motivo;
		public string UserName {
			get {
				return _username;
			}
		}
		public string Reason {
			get {
				return _motivo;
			}
		}		
		public UserEventArgs() { 
			_username = string.Empty;
			_motivo = "timeout";
		
		}
		public UserEventArgs(string way) {
			_username = string.Empty;
			_motivo = way;
		}
		public UserEventArgs(string way,string username) {
			_username = username;
			_motivo = way;
		}				
	}
	public class Ruolo{
		#region Security
		
		public struct SectionsSecurity{
			public bool CanInsert{
				get{
					return _Security[1];
				}
			}
			public bool CanEdit{
				get{
					return _Security[2];
				}
			}
			public bool CanDelete{
				get{
					return _Security[3];
				}
			}
			public bool CanTranslate{
				get{
					return _Security[4];
				}
			}
		}
		
		public struct CategoriesSecurity{
			public bool CanInsert{
				get{
					return _Security[5];
				}
			}
			public bool CanEdit{
				get{
					return _Security[6];
				}
			}
			public bool CanDelete{
				get{
					return _Security[7];
				}
			}
			public bool CanTranslate{
				get{
					return _Security[8];
				}
			}
		}
		
		public struct ArticlesSecurity{
			public bool CanInsert{
				get{
					return _Security[9];
				}
			}
			public bool CanEdit{
				get{
					return _Security[10];
				}
			}
			public bool CanDelete{
				get{
					return _Security[11];
				}
			}
			public bool CanTranslate{
				get{
					return _Security[12];
				}
			}
		}
		
		public struct TemplatesSecurity{
			public bool CanInstall{
				get{
					return _Security[13];
				}
			}
			public bool CanUninstall{
				get{
					return _Security[14];
				}
			}
			public bool CanEdit{
				get{
					return _Security[15];
				}
			}
		}
		
		public bool CanViewStatistics{
			get{
				return _Security[16];
			}
		}
		
		public struct UsersSecurity{
			public bool CanManageUsers{
				get{
					return _Security[17];
				}
			}
			public bool CanManageRoles{
				get{
					return _Security[18];
				}
			}
			public bool CanManageUsersModels{
				get{
					return _Security[19];
				}
			}
			public bool CanManageUsersMenu{
				get{
					return _Security[20];
				}
			}
		}
		
		public struct LayoutSecurity{
			public bool CanManageHP{
				get{
					return _Security[21];
				}
			}
			public bool CanManageViewBlocks{
				get{
					return _Security[22];
				}
			}
			public bool CanManageMenu{
				get{
					return _Security[23];
				}
			}
			public bool CanManageMenuItems{
				get{
					return _Security[24];
				}
			}
		}
		
		public bool isPluginUser{
			get{
				return _Security[25];
			}
		}
		
		public struct ModulesSecurity{
			public bool CanInstall{
				get{
					return _Security[26];
				}
			}
			public bool CanUninstall{
				get{
					return _Security[27];
				}
			}
			public bool CanEdit{
				get{
					return _Security[28];
				}
			}
		}
		
		
		
		public bool isPublisher{
			get{
				return _Security[0];
			}
		}
		
		public SectionsSecurity Sections;
		public CategoriesSecurity Categories;
		public ArticlesSecurity Articles;
		public ModulesSecurity Modules;
		public LayoutSecurity Layout;
		public UsersSecurity Users;
		public TemplatesSecurity Templates;
		#endregion
		private string _name = string.Empty;
		private int _score = 999999;
		//private string _dependson = string.Empty;
		private string[] _dependson = new string[0];
		private string _strsecurity;
		
		static private bool[] _Security = new bool[29];
//			 _isPublisher = false;		0
//			 _SezCanIns = false;
//			 _SezCanEdit = false;
//			 _SezCanDel = false;
//			 _SezCanTrad = false;
//			 _CatCanIns = false;
//			 _CatCanEdit = false;
//			 _CatCanDel = false;
//			 _CatCanTrad = false;
//			 _ArtCanIns = false;
//			 _ArtCanEdit = false;
//			 _ArtCanDel = false;
//			 _ArtCanTrad = false;
//			 _TempCanIns = false;
//			 _TempCanEdit = false;
//			 _TempCanDel = false;
//			 _StatsCanView = false;
//			 _UsersMan = false;
//			 _RolesMan = false;
//			 _UserModelsMan = false;
//			 _UsersMenuMan = false;
//			 _HPMan = false;
//			 _VBMan = false;
//			 _MenuMan = false;
//			 _MenuItemMan = false;
//			 _PluginsMan = false;
//			 _ModulesCanIns = false;
//			 _ModulesCanEdit = false;
//			 _ModulesCanDel = false;	28
		
	//	bool _isProtected = false;
		
		
		public Ruolo(){
			
		}
		public Ruolo(string name){
			if(name.Trim()==""){
				
				return;
			}
			//ACM.cmsarea08.mainconfiguration.MainLogger.logger.SetLogUnique("SONO I RUOLI SENZA PARM","RUOLI","RUOLI");
			ACM.cmsarea08.DBManager.DBClass dclass = new ACM.cmsarea08.DBManager.DBClass();
			string query = "SELECT urole.ruolo, ifnull(urole.dipendenze,'') as dipendenze, punti, security " +
                                                " FROM `"+ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle+"ruoli` as urole " +
                    							" WHERE ruolo = '"+name+"' limit 1;";
			DataRow dr = dclass.Hstandard_ReadRow(query);
			if(dr==null){
				
				return;
			}
			string nome = dr["ruolo"].ToString();
			int sc = Convert.ToInt32(dr["punti"].ToString());
			string sec = dr["security"].ToString();
			
			string tmpRoleNames = "";
			string dipendenze = dr["dipendenze"].ToString();
			string tempDip =dipendenze.Trim();
                
                
                int conto = 0;
                while(tempDip!=string.Empty) {
                
            		object letto = dclass.HStandard_SC(" select ifnull(mastrole.dipendenze,'') as dipendenze  " +
							" from `"+ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle+"ruoli` as mastrole " +
							" where mastrole.ruolo = '" + tempDip + "' limit 1; ");
            		if(letto==null) 
            			tempDip = string.Empty;
            		else {
            			if(letto is byte[] )
            				tempDip = System.Text.Encoding.UTF8.GetString((byte[])letto);
            			else
            				tempDip = letto.ToString();
            		}
            		if(tempDip.Trim().Length==0) 
            			tempDip= string.Empty;
            		else
            			dipendenze+= tempDip + ",";
					conto++;            		
               }
                if(dipendenze.Length>1) 
                	tmpRoleNames += dipendenze; 
				
                tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
                string[] dipe = tmpRoleNames.Split(',');
				
                
               _name=nome;
				_score=sc;
				_dependson=dipe;
				_strsecurity=sec;
			//	ACM.cmsarea08.mainconfiguration.MainLogger.logger.SetLogUnique("VALORI: " + string.Join(", ",dipe),"RUOLI","RUOLI");
				CalcolaPermessi();
				return;
			
			
		
		}
		public Ruolo(string name, int score, string[] dependSon,string Security){
			//ACM.cmsarea08.mainconfiguration.MainLogger.logger.SetLogUnique("SONO I RUOLI PARM","RUOLI","RUOLI");
			_name=name;
			_score=score;
			_dependson=dependSon;
			_strsecurity=Security;
			//ACM.cmsarea08.mainconfiguration.MainLogger.logger.SetLogUnique("VALORI: " + string.Join(", ",dependSon),"RUOLI","RUOLI");
			
			CalcolaPermessi();
			return;
		}
		
		public string Name{
			get{
				return _name;
			}
//			set{
//				_name = value;
//			}
		}
		public int Score{
			get{
				return _score;
			}
//			set{
//				_score = value;
//			}
		}
		public string[] DependSon{
			get{
				return _dependson;
			}
//			set{
//				_dependson = value;
//			}
		}
		public string SecurityString{
			get{
				return _strsecurity;
			}
//			set{
//				_dependson = value;
//			}
		}
		public override string ToString() {
			return _name;
		}
		private void CalcolaPermessi(){
			if(_strsecurity==string.Empty || _strsecurity.Length!=30)
				return;
			char[] caratteri = _strsecurity.ToCharArray();
			
			for(int i=0;i<_Security.Length;i++){
				_Security[i] = (caratteri[i]=='1'?true:false);
			}
			
		}
	
	
	}
	
}

